package com.cgsd.heyu.ui.task;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.library.adapter.OnViewHelper;
import com.android.library.adapter.ViewHelper;
import com.android.library.image.GlideUtil;
import com.android.library.utils.LogUtils;
import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiConfig;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.api.AppConfig;
import com.cgsd.heyu.common.Helper;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.ui.BasePickerFragment;
import com.cgsd.heyu.ui.task.adapter.StepTwoAdapter;
import com.cgsd.heyu.ui.task.vo.EditStepTwoVo;
import com.cgsd.heyu.ui.task.vo.EditThreeVo;
import com.cgsd.heyu.ui.task.vo.TempStepTwoBean;
import com.cgsd.heyu.ui.task.vo.UploadVo;
import com.cgsd.heyu.utils.RequestParams;
import com.cgsd.heyu.widgets.dialog.ConfirmDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.google.gson.Gson;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/3 15:56
 * Email: xcode126@126.com
 * Desc: 新建任务-步骤信息
 * <p>
 * 这里的上传  用七牛云的skd
 * https://developer.qiniu.com/kodo/1664/android-sdk-6
 * 七牛云需要的auth和key
 * http://demo.cgsd163.com:80/api/v1/config/qiniu
 */


public class StepTwoFragment extends BasePickerFragment implements View.OnClickListener {

    private RecyclerView mRecyclerView;
    private StepTwoAdapter stepAdapter;
    private int currentPosition = -1;
    private LinearLayoutManager linearLayoutManager;
    private View headerView;

    public static StepTwoFragment newInstance() {
        return new StepTwoFragment();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_two_step;
    }

    @Override
    protected void initView() {
        findViewById(R.id.tv_last).setOnClickListener(this);
        findViewById(R.id.tv_next).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        initAdapter();

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_last:
                skipStep(true, null);
                break;
            case R.id.tv_next:
            case R.id.tv_save:
                String errorTip = stepAdapter.checkInput();
                if (!TextUtils.isEmpty(errorTip)) {
                    showToast(errorTip);
                    return;
                }

                int tid = getTid();
                if (tid == -1) {
                    showToast(getString(R.string.a_config_error_tip));
                    return;
                }
                String saveParam = stepAdapter.getSaveParam();
                LogUtils.i("sky", "发布任务第二步，tid=" + tid + ",保存参数==" + saveParam);
                saveStepTwo(saveParam, tid);
                break;
        }
    }

    /**
     * init adapter
     */
    private void initAdapter() {
        mRecyclerView = findViewById(R.id.mRecyclerView);
        stepAdapter = new StepTwoAdapter();
        stepAdapter.setHeaderView(getHeaderView());
        linearLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(stepAdapter);
        stepAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                TempStepTwoBean.StepListBean item = stepAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.iv_example:
                        if (TextUtils.isEmpty(item.image)) {
                            currentPosition = position;
                            showPictureSelector(StepTwoFragment.this, 1, true, true);
                        }
                        break;
                    case R.id.iv_close:
                        item.image = "";
                        stepAdapter.notifyItemChanged(position + 1);
                        break;
                    case R.id.ll_no:
                        item.backcom = 0;
                        item.backimg = 0;
                        stepAdapter.notifyItemChanged(position + 1);
                        break;
                    case R.id.ll_picture:
                        item.backcom = 0;
                        item.backimg = 1;
                        stepAdapter.notifyItemChanged(position + 1);
                        break;
                    case R.id.ll_text:
                        item.backcom = 1;
                        item.backimg = 0;
                        stepAdapter.notifyItemChanged(position + 1);
                        break;
                    case R.id.tv_delete:
                        confirmDialog(position);
                        break;
                }
            }
        });
        // 开启拖拽
        ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(stepAdapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
        itemTouchHelper.attachToRecyclerView(mRecyclerView);
        stepAdapter.enableDragItem(itemTouchHelper, R.id.ll_foot, true);
        stepAdapter.setOnItemDragListener(new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int i) {
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder viewHolder, int i, RecyclerView.ViewHolder viewHolder1, int i1) {
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int i) {
                stepAdapter.updateData();
            }
        });
        // 开启滑动删除
//        stepAdapter.enableSwipeItem();
//        stepAdapter.setOnItemSwipeListener(new OnItemSwipeListener() {
//            @Override
//            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int i) {
//
//            }
//
//            @Override
//            public void clearView(RecyclerView.ViewHolder viewHolder, int i) {
//
//            }
//
//            @Override
//            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int i) {
//                stepAdapter.getData().remove(i);
//                stepAdapter.updateData();
//            }
//
//            @Override
//            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float v, float v1, boolean b) {
//                canvas.drawColor(ContextCompat.getColor(getActivity(), R.color.app_color));
//            }
//        });
    }

    /**
     * get heard view
     *
     * @return
     */
    private View getHeaderView() {
        this.headerView = getHelperView(mRecyclerView, R.layout.header_step_two, new OnViewHelper() {
            @Override
            public void help(ViewHelper helper) {
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.ll_add:
                                int count = stepAdapter.getItemCount();
                                stepAdapter.addData(new TempStepTwoBean.StepListBean(count));
                                linearLayoutManager.setStackFromEnd(true);
                                linearLayoutManager.scrollToPositionWithOffset(count, Integer.MIN_VALUE);
                                break;
                            case R.id.iv_video:
                                showPictureSelector(StepTwoFragment.this, 1, true, true, true);
                                currentPosition = -1;
                                break;
                            case R.id.iv_close:
                                handleHeaderImage("");
                                break;
                        }

                    }
                }, R.id.ll_add, R.id.iv_video, R.id.iv_close);
            }
        });
        return headerView;
    }

    /**
     * @param isLast 是否跳到上一步
     */
    private void skipStep(boolean isLast, EditThreeVo threeVo) {
        if (getActivity() instanceof PublishTaskActivity) {
            PublishTaskActivity activity = (PublishTaskActivity) getActivity();
            activity.setEditThreeVo(threeVo);
            activity.setCurrentPage(isLast ? 0 : 2);
        }
    }

    /**
     * 获取任务id
     *
     * @return
     */
    private int getTid() {
        if (getActivity() instanceof PublishTaskActivity) {
            PublishTaskActivity activity = (PublishTaskActivity) getActivity();
            return activity.getTid();
        }
        return -1;
    }

    @Override
    public void obtainMediaResult(List<LocalMedia> list) {
        if (list != null && list.size() > 0) {
            LocalMedia localMedia = list.get(0);
            String path;
            if (currentPosition == -1) {//头部
                path = localMedia.getRealPath();
                if (TextUtils.isEmpty(path)) {
                    showToast("视频路径为空");
                    return;
                }
            } else {
                path = localMedia.getCompressPath();
                if (TextUtils.isEmpty(path)) {
                    showToast("照片路径为空");
                    return;
                }
            }
            uploadFile(path);

            com.apkfuns.logutils.LogUtils.e("上传路径 ：" + path);
            //testUploadVideo(path);
        }
    }
    String auth="oxC9pxS73_5rLJbZ89c-owOwJTQTJ0J3wlRulD0p:2r8jE9XzDujSVd3FRa3LHQjIBM8=:eyJzY29wZSI6InBob3RvLWRpYXJ5IiwiZGVhZGxpbmUiOjE2MTg5OTE0Nzl9";
    String key="1618976080582588";
    private void testUploadVideo(String path) {
        UploadManager uploadManager = new UploadManager();
        uploadManager.put(new File(path), key, auth, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                com.apkfuns.logutils.LogUtils.e("complete "+key+"\n"+info.toString()+"\n "+response.toString());
            }
        },uploadOptions);
    }

    UploadOptions uploadOptions = new UploadOptions(null, null, false,
            new UpProgressHandler() {
                @Override
                public void progress(String key, double percent) {
                    com.apkfuns.logutils.LogUtils.e(key+" -- "+percent);
                }
            }, null);
//
    /**
     * upload file
     *
     * @param path
     */
    public void uploadFile(String path) {
        showSubmitDialog();
        File file = new File(path);


        OkGo.<String>post(AppConfig.BASE_PHP_URL + "/" + ApiConfig.API_UPLOAD_FILE)
                .tag(this)
                .params("file", file)
                .headers("token", Helper.getTokenPhpInfo())
                .isMultipart(true)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        processUploadFile(response);
                        dismissCommonSubmitDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        showToast("操作异常，请稍后重试");
                        dismissCommonSubmitDialog();
                    }
                });

    }

    /**
     * 处理上传文件
     *
     * @param response
     */
    private void processUploadFile(Response<String> response) {
        try {
            UploadVo uploadVo = new Gson().fromJson(response.body(), UploadVo.class);
            com.apkfuns.logutils.LogUtils.e("sky"+"上传图片返回：" + response.body());
            if (currentPosition == -1) {//0是头部
                handleHeaderImage(uploadVo.bizBody.fullurl);
            } else {
                TempStepTwoBean.StepListBean item = stepAdapter.getItem(currentPosition);
                item.image = uploadVo.bizBody.fullurl;
                stepAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            showToast("解析数据异常，请稍后重试");
        }
    }

    /**
     * handle header image
     *
     * @param url todo
     */
    private void handleHeaderImage(String url) {
        stepAdapter.video = url;
        com.apkfuns.logutils.LogUtils.e("上传  url " + url);
        ImageView ivVideo = headerView.findViewById(R.id.iv_video);
        if (TextUtils.isEmpty(url)) {//没添加图片
            headerView.findViewById(R.id.iv_close).setVisibility(View.GONE);
            GlideUtil.loadLocalImage(R.mipmap.ic_add_picture, ivVideo);
            ivVideo.setEnabled(true);
        } else {
            headerView.findViewById(R.id.iv_close).setVisibility(View.VISIBLE);
            GlideUtil.loadVideoImage(mContext, url, ivVideo);
            ivVideo.setEnabled(false);
        }
    }

    /**
     * 保存第二步数据
     *
     * @param param
     * @param tid
     */
    private void saveStepTwo(String param, int tid) {
        showSubmitDialog();//return new GsonBuilder().serializeNulls().create().toJson(list);
        RequestBody requestBody = new RequestParams()
                .put("taskdata", param)
                .put("tid", tid)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .saveStepTwo(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<EditThreeVo>>() {
                    @Override
                    public void onSuccess(BaseResponse<EditThreeVo> baseResponse) {
                        dismissCommonSubmitDialog();
                        showToast(baseResponse.getResultMsg());
                        processEditData(baseResponse.getBizBody());
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        handleErrorAction(error);
                        dismissCommonSubmitDialog();
                    }
                });
    }

    /**
     * 处理之前编辑的第二部数据
     *
     * @param twoVo
     */
    private void processEditData(EditThreeVo twoVo) {
        skipStep(false, twoVo);
    }

    @Override
    public void onRefresh(Object t) {
        List<TempStepTwoBean.StepListBean> list = new ArrayList<>();
        if (t != null && t instanceof EditStepTwoVo) {
            EditStepTwoVo editStepTwoVo = (EditStepTwoVo) t;
//            initView();
            if (editStepTwoVo != null) {
                handleHeaderImage(editStepTwoVo.video);
                if (editStepTwoVo.step != null && editStepTwoVo.step.size() > 0) {
                    for (EditStepTwoVo.StepBean stepBean : editStepTwoVo.step) {
                        TempStepTwoBean.StepListBean bean = new TempStepTwoBean.StepListBean(stepBean.step);
                        bean.backcom = stepBean.backcom;
                        bean.backimg = stepBean.backimg;
                        bean.content = stepBean.content;
                        bean.title = stepBean.title;
                        bean.image = stepBean.image;
                        list.add(bean);
                    }
                } else {
                    list.add(new TempStepTwoBean.StepListBean(1));
                    list.add(new TempStepTwoBean.StepListBean(2));
                }
            } else {
                list.add(new TempStepTwoBean.StepListBean(1));
                list.add(new TempStepTwoBean.StepListBean(2));
            }
        } else {
            list.add(new TempStepTwoBean.StepListBean(1));
            list.add(new TempStepTwoBean.StepListBean(2));
        }
        stepAdapter.setNewData(list);
    }

    private ConfirmDialog confirmDialog;

    /**
     * 确定是否删除
     */
    private void confirmDialog(int position) {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(getActivity());
            confirmDialog.setTitle("确认是否删除？");
            confirmDialog.setDialogListener(new ConfirmDialog.DialogListener() {
                @Override
                public void confirm() {
                    stepAdapter.getData().remove(position);
                    stepAdapter.notifyDataSetChanged();
                    confirmDialog.dismiss();

                }

                @Override
                public void cancel() {
                    confirmDialog.dismiss();
                }
            });
        }
        confirmDialog.show();
    }
}
